﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RexToy.Json
{
    public class DateTimeConverter : IExtendConverter
    {
        public const int TIME_FACTOR = 10000;
        public static readonly long DateTimeMinTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

        #region IExtendConverter Members

        public bool CanConvert(Type t)
        {
            return t == typeof(DateTime) || t == typeof(DateTime?);
        }

        public string ToJsonString(object instance)
        {
            if (instance == null)
                return null;

            StringBuilder str = new StringBuilder();
            DateTime time = (DateTime)instance;
            str.Append(@"""\/Date(");
            str.Append((time.ToUniversalTime().Ticks - DateTimeMinTimeTicks) / TIME_FACTOR);
            str.Append(@")\/""");

            return str.ToString();
        }

        public object FromJsonString(Type t, string json, bool ignoreTypeSafe = false)
        {
            if (string.IsNullOrEmpty(json))
                return null;
            Assertion.IsTrue(json.StartsWith("\"\\/Date(") && json.EndsWith(")\\/\""), "JSON Datetime extend format not correct.");
            return new DateTime(long.Parse(json.Split('(', ')')[1]) * TIME_FACTOR + DateTimeMinTimeTicks).ToLocalTime();
        }

        #endregion
    }
}
